package com.wnhz.work.yz.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.wnhz.work.yz.BaseActivity;
import com.wnhz.work.yz.MyApplication;
import com.wnhz.work.yz.R;
import com.wnhz.work.yz.base.BaseRVAdapter;
import com.wnhz.work.yz.base.BaseViewHolder;
import com.wnhz.work.yz.bean.CustomerTypeBean;
import com.wnhz.work.yz.bean.ProductBean;
import com.wnhz.work.yz.bean.RecordDetailBean;
import com.wnhz.work.yz.utils.Url;
import com.wnhz.work.yz.utils.xutils3.MyCallBack;
import com.wnhz.work.yz.utils.xutils3.XUtil;
import com.wnhz.work.yz.view.SwitchView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class LookDetailsActivity extends BaseActivity implements View.OnClickListener {
    private static final int LOOKNUM = 123;

    private void bindViews() {

        mCustomer_name = (TextView) findViewById(R.id.customer_name);
        mCustomer_address_click = (TextView) findViewById(R.id.customer_address_click);
        mCustomer_desicAdd = (TextView) findViewById(R.id.customer_desicAdd);
        mSwitchButton = (SwitchView) findViewById(R.id.switchButton);
        mName = (TextView) findViewById(R.id.name);
        mAddress_click = (TextView) findViewById(R.id.address_click);
        mDesicAdd = (TextView) findViewById(R.id.desicAdd);
        mLook = (TextView) findViewById(R.id.look);
        mNums = (TextView) findViewById(R.id.nums);
        mAll_money = (TextView) findViewById(R.id.all_money);
        mRivla_img1 = (ImageView) findViewById(R.id.rivla_img1);
        mRivla2 = (LinearLayout) findViewById(R.id.rivla2);
        mRivla_img2 = (ImageView) findViewById(R.id.rivla_img2);
        mAdd_person = (TextView) findViewById(R.id.add_person);
        mRecycler_person = (RecyclerView) findViewById(R.id.recycler_person);
        project_nums = (TextView) findViewById(R.id.project_nums);
    }

    private void getCustomerType() {
        showDialog();
        XUtil.Post(Url.API_RECORD, null, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Gson gson = new Gson();
                CustomerTypeBean bean = gson.fromJson(result, CustomerTypeBean.class);
                List<CustomerTypeBean.InfoEntity.CustomerTypeEntity> customerTypeList = bean.getInfo().getCustomer_type();
                infoType = new ArrayList<String>();
                for (int i = 0; i < customerTypeList.size(); i++) {
                    infoType.add(customerTypeList.get(i).getClassname());
                }

            }

            @Override
            public void onFinished() {

                try {
                    mCustomer_type.setText("" + infoType.get(Integer.parseInt(info.getCustomer_type())-1));
                    closeDialog();
                } catch (Exception e) {
                    if (!isFirst) {
                        getCustomerType();
                        isFirst = true;
                    }
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
            }
        });
    }

    boolean isFirst = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_look_details);
        mCustomer_type = (TextView) findViewById(R.id.customer_type);
        initData();
        initTitle();
        bindViews();
    }

    private void initTitle() {
        findViewById(R.id.btn_main_left).setOnClickListener(this);
        TextView title = (TextView) findViewById(R.id.view_main_middle_title);
        title.setText("精确信息");
        TextView submit = (TextView) findViewById(R.id.submit);
        submit.setText("引用记录");
        if (getIntent().getIntExtra("isisis", 0) == 0) {
            submit.setVisibility(View.VISIBLE);
        } else {
            title.setText("备案详细信息");
        }
        submit.setOnClickListener(this);
    }


    private String recordid;
    private String user_id;

    private void initData() {
        recordid = getIntent().getStringExtra("recordid");
        user_id = getIntent().getStringExtra("user_id");
        getCustomerType();
        upLoad();
    }

    private RecordDetailBean.InfoEntity info = new RecordDetailBean.InfoEntity();
    private List<RecordDetailBean.InfoEntity.ProjectTypeEntity> project_type = new ArrayList<>();
    private List<RecordDetailBean.InfoEntity.ContactPersonEntity> contact_person = new ArrayList<>();
    private ArrayList<String> infoType = new ArrayList<>();

    private void upLoad() {
        showDialog();
        Map<String, Object> map = new HashMap<>();
        map.put("token", MyApplication.getInstance().getUserBean().getToken());
        map.put("recordid", recordid);
        if (user_id != null)
            map.put("user_id", user_id);
        XUtil.Post(Url.API_RECORDDETAIL, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.e("----", result);
                Gson gson = new Gson();
                RecordDetailBean bean = gson.fromJson(result, RecordDetailBean.class);
                if (bean.getResult().equals("1")) {
                    info = bean.getInfo();
                    project_type = info.getProject_type();
                    contact_person = info.getContact_person();
                }
            }

            @Override
            public void onFinished() {
                closeDialog();
                setData();
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
            }
        });
    }

    private TextView mCustomer_name;
    private TextView project_nums;
    private TextView mCustomer_address_click;
    private TextView mCustomer_desicAdd;
    private SwitchView mSwitchButton;
    private TextView mCustomer_type;
    private TextView mName;
    private TextView mAddress_click;
    private TextView mDesicAdd;
    private TextView mLook;
    private TextView mNums;
    private TextView mAll_money;
    private ImageView mRivla_img1;
    private LinearLayout mRivla2;
    private ImageView mRivla_img2;
    private TextView add_person;
    private TextView mAdd_person;
    private RecyclerView mRecycler_person;
    private Button submit_all;


    private void setData() {
        mCustomer_name.setText(info.getCustomer_name());
        mAddress_click.setText(info.getProject_province() + "-" + info.getProject_city() + "-" + info.getProject_district());
        mCustomer_address_click.setText(info.getCustomer_province() + "-" + info.getCustomer_city() + "-" + info.getCustomer_district());
        mCustomer_desicAdd.setText(info.getCustomer_address());
        mName.setText(info.getProject_name());
        mDesicAdd.setText("" + info.getProject_address());
        mNums.setText("" + info.getProject_num());
        mAll_money.setText("" + info.getBudget_money());
        String str[] = info.getCompet_person().split("-");
        Log.e("----+" + str[0] + "," + str[1], "--" + info.getCompet_person());


        mRivla_img1.setImageResource(str[0].equals("0") ? R.mipmap.ic_choose_nor : R.mipmap.ic_choose_li);
        mRivla_img2.setImageResource(str[1].equals("0") ? R.mipmap.ic_choose_nor : R.mipmap.ic_choose_li);
        project_nums.setText(info.getProject_no());
        submit_all = (Button) findViewById(R.id.submit_all);
        submit_all.setVisibility(View.GONE);
        mSwitchButton.setFlag(false);
        mSwitchButton.setOpened(info.getCustomer_is_area().equals("1") ? true : false);

        mLook = (TextView) findViewById(R.id.look);
        mLook.setOnClickListener(this);
        mRecycler_person = (RecyclerView) findViewById(R.id.recycler_person);
        mRecycler_person.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        if (contact_person.size() > 0) {
            mRecycler_person.setVisibility(View.VISIBLE);
        }
        AddPersonAdapter addPersonAdapter = new AddPersonAdapter(this, contact_person);
        mRecycler_person.setAdapter(addPersonAdapter);
    }

    class AddPersonAdapter extends BaseRVAdapter {
        private List<RecordDetailBean.InfoEntity.ContactPersonEntity> contact_person = new ArrayList<>();

        /**
         * 构造器
         *
         * @param context 上下文
         * @param list    数据集合
         */
        public AddPersonAdapter(Context context, @NonNull List list) {
            super(context, list);
            contact_person = list;

        }

        @Override
        public int getLayoutId(int viewType) {
            return R.layout.item_add_person;
        }

        @Override
        public void onBind(BaseViewHolder holder, final int position) {
            holder.setImageResource(R.id.img_head, R.mipmap.headportrait);
            holder.setTextView(R.id.text_name, contact_person.get(position).getName());
//            holder.getView(R.id.delete).setVisibility(View.VISIBLE);

            holder.getView(R.id.delete).setVisibility(View.GONE);
//            holder.getView(R.id.delete).setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//
//                    showDialogv7("确定删除该联系人吗？", new DialogInterface.OnClickListener() {
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
//                            contact_person.remove(position);
//                        }
//                    });
//                    if (contact_person.size() <= 0) {
//                        mRecycler_person.setVisibility(View.GONE);
//                    }
//                }
//            });
            holder.getView(R.id.img_head).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(LookDetailsActivity.this);
                    final View view = View.inflate(LookDetailsActivity.this, R.layout.dialog_person, null);
                    final TextView name, phone, job, email, wx_num;
                    name = (TextView) view.findViewById(R.id.name);
                    phone = (TextView) view.findViewById(R.id.phone);
                    job = (TextView) view.findViewById(R.id.job);
                    email = (TextView) view.findViewById(R.id.email);
                    wx_num = (TextView) view.findViewById(R.id.wx_num);
                    name.setText(contact_person.get(position).getName());
                    phone.setText(contact_person.get(position).getTelphone());
                    job.setText(contact_person.get(position).getJob());
                    email.setText(contact_person.get(position).getEmail());
                    wx_num.setText(contact_person.get(position).getWx());

                    builder.setView(view);
                    final AlertDialog show = builder.show();
                    Window dialogWindow = show.getWindow();
                    WindowManager.LayoutParams lp = dialogWindow.getAttributes();
                    dialogWindow.setGravity(Gravity.CENTER);
                    // lp.x = 100; // 新位置X坐标
                    lp.width = getWindowManager().getDefaultDisplay().getWidth() / 3 * 2; // 宽度
                    dialogWindow.setAttributes(lp);
                    TextView cancel = (TextView) view.findViewById(R.id.cancel33);
                    TextView call = (TextView) view.findViewById(R.id.call);
                    cancel.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            show.dismiss();
                        }
                    });
                    call.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            AlertDialog.Builder builder = new AlertDialog.Builder(LookDetailsActivity.this);
                            builder.setMessage("即将跳往拨打电话界面");

                            builder.setTitle("联系人");

                            builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {

                                    Intent intent2 = new Intent(Intent.ACTION_DIAL);
                                    Uri data = Uri.parse("tel:" + phone.getText());
                                    intent2.setData(data);
                                    startActivity(intent2);
                                }
                            });

                            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            });
                            builder.create().show();

                        }
                    });

                }
            });
        }


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_main_left:
                finish();
                break;
            case R.id.look:
                Intent intent2 = new Intent(this, SelectProductActivity.class);
                ArrayList<ProductBean> data = new ArrayList<>();
                for (int i = 0; i < project_type.size(); i++) {
                    ProductBean b = new ProductBean();
                    b.setNumber(Integer.parseInt(project_type.get(i).getNums()));
                    b.setInfoId(project_type.get(i).getTop_cate_id());
                    b.setDetailId(project_type.get(i).getTwo_cate_id());
                    b.setDetail_goodsId(project_type.get(i).getBathgoods_id());
                    b.setInfoStr(project_type.get(i).getTop_cate_name());
                    b.setDetailStr(project_type.get(i).getTwo_cate_name());
                    b.setDetail_goodsStr(project_type.get(i).getBathgoods_name());
                    data.add(b);
                }
                intent2.putExtra("isLook", 1);
                intent2.putExtra("data", data);
                startActivity(intent2);
                break;
            case R.id.submit:
                Intent intent3 = new Intent(this, RecordUsedListActivity.class);
                intent3.putExtra("recordid", recordid);
                startActivity(intent3);


                break;
        }
    }
}
